package com.example.battle.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.ActionBar;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.battle.R;
import com.example.battle.db.BattleDao;
import com.example.battle.entity.User;
import com.example.battle.ui.fragment.PersonFragment;
import com.example.battle.util.ActivityCollector;
import com.example.battle.util.CityBean;
import com.example.battle.util.PhotoUtils;
import com.example.battle.util.ProvinceBean;
import com.example.battle.util.ToastUtils;
import com.example.battle.widget.ItemGroup;
import com.example.battle.widget.RoundImageView;
import com.example.battle.widget.TitleLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


public class PersonInfo extends AppCompatActivity implements View.OnClickListener {
    private ItemGroup ig_id,ig_name,ig_gender,ig_region,ig_brithday;
    private LinearLayout ll_portrait;
    private RoundImageView ri_portrait;
    private TitleLayout titleLayout;
    private User user;

    private ToastUtils mToast = new ToastUtils();

    private ArrayList<String> optionsItems_gender = new ArrayList<>();
    private ArrayList<ProvinceBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();

    private OptionsPickerView pvOptions;

    private PhotoUtils photoUtils = new PhotoUtils();

    private BattleDao battleDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);

        initOptionData();

        ig_id = (ItemGroup)findViewById(R.id.ig_id);
        ig_name = (ItemGroup)findViewById(R.id.ig_name);
        ig_gender = (ItemGroup)findViewById(R.id.ig_gender);
        ig_region = (ItemGroup)findViewById(R.id.ig_region);
        ig_brithday = (ItemGroup)findViewById(R.id.ig_brithday);
        ll_portrait = (LinearLayout)findViewById(R.id.ll_portrait);
        ri_portrait = (RoundImageView)findViewById(R.id.ri_portrait);
        titleLayout = (TitleLayout)findViewById(R.id.tl_title);

        Intent intent = getIntent();
        user = (User) intent.getSerializableExtra("user");
        initInfo(user);

        titleLayout.findViewById(R.id.tv_title);

        ig_name.setOnClickListener(this);
        ig_gender.setOnClickListener(this);
        ig_region.setOnClickListener(this);
        ig_brithday.setOnClickListener(this);
        ll_portrait.setOnClickListener(this);

        //设置点击保存的逻辑
        titleLayout.getTextView_forward().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 保存
                battleDao = Login.getInstance().getAppDB().battleDao();
                user.setPassword(battleDao.login(user.getUserId()).getPassword());
                battleDao.updateUserInfo(user);
                mToast.showShort(PersonInfo.this,"保存成功");
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //点击修改地区逻辑
            case R.id.ig_region:
                pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String tx = options1Items.get(options1).getPickerViewText()
                                + options2Items.get(options1).get(options2);
                        ig_region.getContentEdt().setText(tx);
                        user.setRegion(tx);
                    }
                }).setCancelColor(Color.GRAY).build();
                pvOptions.setPicker(options1Items, options2Items);//二级选择器
                pvOptions.show();
                break;

            //点击修改性别逻辑
            case R.id.ig_gender:
                //性别选择器
                pvOptions = new OptionsPickerBuilder(PersonInfo.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                        //选择了则显示并暂存LoginUser，退出时在保存至数据库
                        String tx = optionsItems_gender.get(options1);
                        ig_gender.getContentEdt().setText(tx);
                        if (tx.equals("男")){
                            user.setGender(1);
                        }else if(tx.equals("女")){
                            user.setGender(2);
                        }else {
                            user.setGender(0);
                        }
                    }
                }).setCancelColor(Color.GRAY).build();
                pvOptions.setPicker(optionsItems_gender);
                pvOptions.show();
                break;

            //点击修改生日逻辑
            case R.id.ig_brithday:
                //时间选择器
                //修改打开的默认时间，如果选择过则是选择过的时间，否则是系统默认时间
                Calendar selectedDate = Calendar.getInstance();
                if (user.getBirth() != null){
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        selectedDate.setTime(sdf.parse(user.getBirth()));
                    }catch (ParseException e){
                        e.printStackTrace();
                    }
                }
                //初始化picker并show
                TimePickerView pvTime = new TimePickerBuilder(PersonInfo.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        ig_brithday.getContentEdt().setText(sdf.format(date));
                        user.setBirth(sdf.format(date));
                    }
                }).setDate(selectedDate).setCancelColor(Color.GRAY).build();
                pvTime.show();
                break;
            //点击修改名字的逻辑
            case R.id.ig_name:
                Intent intent  = new Intent(PersonInfo.this, EditName.class);
                intent.putExtra("user",user);
                startActivity(intent);
                break;
            default:
                break;
        }
    }


    private void initInfo(User user){
        ig_id.getContentEdt().setText(user.getUserId());  //ID是int，转string
        ig_name.getContentEdt().setText(user.getUserName());
        if (user.getPortrait() != null){
            ri_portrait.setImageBitmap(photoUtils.byte2bitmap(user.getPortrait()));
        }
        switch (user.getGender()){
            case 1:
                ig_gender.getContentEdt().setText("男");
                break;
            case 2:
                ig_gender.getContentEdt().setText("女");
                break;
            default:
                ig_gender.getContentEdt().setText("保密");
                break;
        }
        if (user.getRegion() != null){
            ig_region.getContentEdt().setText(user.getRegion());
        }
        if (user.getRegion() != null){
            ig_brithday.getContentEdt().setText(user.getBirth());
        }
    }


    //初始化性别、地址和生日的数据
    private void initOptionData(){
        //性别选择器数据
        optionsItems_gender.add(new String("保密"));
        optionsItems_gender.add(new String("男"));
        optionsItems_gender.add(new String("女"));

        //地址选择器数据
        String province_data = readJsonFile("province.json");
        String city_data = readJsonFile("city.json");

        Gson gson = new Gson();

        options1Items = gson.fromJson(province_data, new TypeToken<ArrayList<ProvinceBean>>(){}.getType());
        ArrayList<CityBean> cityBean_data = gson.fromJson(city_data, new TypeToken<ArrayList<CityBean>>(){}.getType());
        for(ProvinceBean provinceBean:options1Items){
            ArrayList<String> temp = new ArrayList<>();
            for (CityBean cityBean : cityBean_data){
                if(provinceBean.getProvince().equals(cityBean.getProvince())){
                    temp.add(cityBean.getName());
                }
            }
            options2Items.add(temp);
        }

    }

    //传入：asset文件夹中json文件名
    //返回：读取的String
    private String readJsonFile(String file){
        StringBuilder newstringBuilder = new StringBuilder();
        try {
            InputStream inputStream = getResources().getAssets().open(file);

            InputStreamReader isr = new InputStreamReader(inputStream);

            BufferedReader reader = new BufferedReader(isr);

            String jsonLine;
            while ((jsonLine = reader.readLine()) != null) {
                newstringBuilder.append(jsonLine);
            }
            reader.close();
            isr.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data =  newstringBuilder.toString();
        return data;
    }

}
